import React, { useEffect } from 'react';
import { useLocation } from '@docusaurus/router';
import { parse as parseUserAgent } from '@site/src/utils/userAgent';

const Login: React.FC = () => {
  const location = useLocation();
  const params = new URLSearchParams(location.search);
  const from = params.get('from') || '/';

  useEffect(() => {
    if (!from.startsWith('/')) {
      window.location.href = '/';
      return;
    }

    const userAgent = parseUserAgent(navigator.userAgent);
    const base = `${window.location.protocol}//${window.location.host}`;
    const redirect = `${base}/callback?from=${encodeURIComponent(from)}`;

    let loginPath = '';

    if (userAgent.browser.name === 'WeChat') {
      loginPath = `https://openatom.tech/callback?transfer_redirect=${encodeURIComponent(redirect)}&transfer_type=wechat`;
    }
    else {
      loginPath = `https://openatom.tech/callback?transfer_redirect=${encodeURIComponent(redirect)}`;
    }

    window.location.replace(loginPath);
  }, [from]);

  return (
    <main>
      正在登录，请稍候...
    </main>
  );
};

export default Login;
